package com.lagou.executor;

import com.lagou.conf.Configuration;
import com.lagou.conf.MappedStatement;
import com.mchange.v2.util.CollectionUtils;
import com.mchange.v3.hocon.HoconUtils;
import org.junit.Test;


import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor {
    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        Connection connection = configuration.getDataSource().getConnection();
        // select * from user where id = #{id} and username = #{username}
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        String finalSql = boundSql.getSql();
        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
        // 一条sql中多个参数集合
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        // 输入参数类型
        Class<?> paramterType = mappedStatement.getParamterType();

        if (parameterMappingList != null && parameterMappingList.size() > 0) {
            // 遍历参数 where a = #{a} and b = #{b} and c = #{c}
            for (int i = 1; i <= parameterMappingList.size(); i++) {
                // 获取参数名
                String name = parameterMappingList.get(i - 1).getName();
                Field declaredField = paramterType.getDeclaredField(name);
                declaredField.setAccessible(true);
                // 映射输入参数的值
                Object o = declaredField.get(param[0]);
                // 给占位符设置值
                preparedStatement.setObject(i, o);
            }
        }

        ResultSet resultSet = preparedStatement.executeQuery();
        Class<?> resultType = mappedStatement.getResultType();
        List<E> resultList = new ArrayList<>();

        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            int columnCount = metaData.getColumnCount();
            Object o = (E) resultType.newInstance();
            for (int i = 1; i <= columnCount; i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultType);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultList.add((E) o);
        }
        return resultList;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... param) throws SQLException, NoSuchFieldException, IllegalAccessException {
        Connection connection = configuration.getDataSource().getConnection();
        // select * from user where id = #{id} and username = #{username}
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        String finalSql = boundSql.getSql();
        PreparedStatement preparedStatement = connection.prepareStatement(finalSql);
        // 一条sql中多个参数集合
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        // 输入参数类型
        Class<?> paramterType = mappedStatement.getParamterType();

        if (parameterMappingList != null && parameterMappingList.size() > 0) {
            // 遍历参数 where a = #{a} and b = #{b} and c = #{c}
            for (int i = 1; i <= parameterMappingList.size(); i++) {
                // 获取参数名
                String name = parameterMappingList.get(i - 1).getName();
                Field declaredField = paramterType.getDeclaredField(name);
                declaredField.setAccessible(true);
                // 映射输入参数的值
                Object o = declaredField.get(param[0]);
                // 给占位符设置值
                preparedStatement.setObject(i, o);
            }
        }
        int i = preparedStatement.executeUpdate();
        preparedStatement.close();
        return i;
    }

    private BoundSql getBoundSql(String sql) {
        //标记处理类：主要是配合通⽤标记解析器GenericTokenParser类完成对配置⽂件等的解析⼯作，其中TokenHandler主要完成处理
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        //GenericTokenParser :通⽤的标记解析器，完成了代码⽚段中的占位符的解析，然后再根据给定的标记处理器(TokenHandler)来进⾏表达式的处理
        //三个参数：分别为openToken (开始标记)、closeToken (结束标记)、handler (标记处 理器)
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);
        String parse = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        return new BoundSql(parse, parameterMappings);
    }

    @Test
    public void testDemo() {
        String sql = "select * from user where id = #{id} and username = #{username}";
        BoundSql boundSql = getBoundSql(sql);
    }
}
